const base64 = require('../utils/base64.js').Base64
const host = process.env.VUE_APP_URL
const global = {
  data() {
    return {
      limit: 20,
      theme_color: '#FF6F1B',
      my_style: `--color:${'#FF6F1B'};`,
      custom_btn: {
        backgroundColor: '#FF6F1B',
      },
      icon_path: `${host}/assets/images/`,
    }
  },
  methods: {
    /**
     * 跳转
     * @param {Object} url
     */
    async jump(url) {
      uni.navigateTo({
        url,
      })
    },
    /**
     * 返回上一页
     */
    goBack(number) {
      const pages = getCurrentPages()
      console.log(pages)
      if (pages.length > 1) {
        uni.navigateBack(number || 1)
        return
      }
      // 使用vue-router返回上一级
      let a = this.$router.go(number || 1)
      if (a == undefined) {
        // 重新定向跳转页面
        uni.switchTab({
          url: '/pages/index/index',
        })
      }
    },
    replaceJump(url) {
      uni.redirectTo({
        url,
      })
    },
    reLaunch(url) {
      uni.reLaunch({
        url,
      })
    },
    switchTab(url) {
      uni.switchTab({
        url,
      })
    },
    // 打电话
    callPhone(phone) {
      uni.makePhoneCall({
        phoneNumber: phone,
      })
    },
    // 图片预览
    previewImage(item, list) {
      uni.previewImage({
        current: item,
        urls: list,
      })
    },
    /**
     * 操作成功并返回
     * @param {Object} msg
     */
    successBack(msg, num) {
      uni.showToast({
        title: msg,
        icon: 'success',
      })
      setTimeout(() => {
        this.goBack(num)
      }, 1000)
    },
    showMsg(msg, icon) {
      uni.showToast({
        icon: icon || 'none',
        title: msg,
      })
    },
    // 复制
    copyText(text) {
      const result = this.h5Copy(text)
      if (result === false) {
        uni.showToast({
          title: '不支持',
        })
      } else {
        uni.showToast({
          title: '复制成功',
          icon: 'none',
        })
      }
    },
    h5Copy(content) {
      if (!document.queryCommandSupported('copy')) {
        // 不支持
        return false
      }
      let textarea = document.createElement('textarea')
      textarea.value = content
      textarea.readOnly = 'readOnly'
      document.body.appendChild(textarea)
      textarea.select() // 选择对象
      textarea.setSelectionRange(0, content.length) // 核心
      let result = document.execCommand('copy') // 执行浏览器复制命令
      textarea.remove()
      return result
    },
    // 成功
    successGo(info) {
      uni.redirectTo({
        url: `/views/user/success${info}`,
      })
    },
    // 刷新
    refreshList(fn) {
      this.page = 1
      this.list = []
      this.status = 'loading'
      fn && fn()
    },
    // 获取主题色
    async getThemeColor() {
      const res = await this.$api.common.system('getThemeColor')
      if (res.code === 200) {
        const { color } = res.data
        uni.setStorageSync('theme_color', color)
      }
    },
    // 去登录
    toLogin() {
      // #ifdef APP-PLUS || H5
      this.jump('/views/login/login')
      // #endif
      // #ifdef MP-WEIXIN
      this.jump('/views/auth/authorize')
      // #endif
    },
    killTime(end_time) {
      let that = this
      let now_time = (new Date().getTime() / 1000).toFixed(0) // 当前时间
      // 剩余时间
      return +end_time - +now_time
    },
    // 随机字符串
    randomStr(len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    isListNone(list) {
      return JSON.stringify(list) !== '[]'
    },
    isObjNone(obj) {
      return JSON.stringify(obj) !== '{}'
    },
    stopClick() {},
    // 内链外链跳转
    customJump(item) {
      console.log(item)
      const { jump_type, jump_id } = item
      switch (Number(jump_type)) {
        // 自定义页面
        case 1:
          wx.navigateTo({
            url: `/views/home/custom?id=${jump_id}`,
          })
          break
        // 商品
        case 2:
          wx.navigateTo({
            url: `/views/goods/goods_detail?id=${jump_id}`,
          })
          break
        // 领券中心
        case 3:
          wx.navigateTo({
            url: `/views/home/coupon_center`,
          })
          break
        default:
      }
    },
    // 设置蓝牙最大传输单元
    setBlueTooth(deviceId) {
      uni.setBLEMTU({
        deviceId,
        mtu: 128,
      })
    },
    // 向蓝牙写入
    writeBLECharacteristicValue(options) {
      let len = options.data.length.toString(16)
      len = len.length > 1 ? len : '0' + len
      // 判断是否是更新写入调用
      var arr
      if (options.num) {
        // 指令和后面数据的数组
        arr = [options.num, len, ...options.data]
      } else {
        arr = [options.header, options.version, len, ...options.data]
      }
      // 给每一项添加'0x'
      let str = arr.map((item) => '0x' + item).join(' ')
      console.log('我正在发送数据【手机向蓝牙模块】', str)
      // 向蓝牙设备发送一个0x00的16进制数据//代表内存之中的一段二进制数据
      const buffer = this.hex2ab(str)
      uni.writeBLECharacteristicValue({
        deviceId: uni.getStorageSync('device_id'), // 设备deviceId
        serviceId: uni.getStorageSync('service_id'), // 设备service_id
        characteristicId: uni.getStorageSync('uuid'), // 设备write特征值
        value: buffer, // 写入数据
        success: (res) => {
          console.log('发送数据:', res)
          uni.hideLoading()
          this.equi_list[this.equi_index].title = this.equi_name
          uni.setStorageSync('device_name', this.equi_name)
          if (uni.getStorageSync('my_list').length > 0) {
            let my_list = uni.getStorageSync('my_list')
            my_list.forEach((item) => {
              if (item.eq_id == uni.getStorageSync('device_id')) {
                item.title = this.equi_name
              }
            })
            uni.setStorageSync('my_list', my_list)
          }
        },
        fail: (err) => {
          console.log('err', err)
        },
      })
    },

    // 16进制字符串转ArrayBuffer示例
    hex2ab(str) {
      const typedArray = new Uint8Array(
        str.match(/[\da-f]{2}/gi).map(function (h) {
          return parseInt(h, 16)
        })
      )
      return typedArray.buffer
    },
    // ArrayBuffer转16进制字符串示例
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      })
      return hexArr.join('')
    },
    // 为了去除重复的
    inArray(arr, key, val) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
          return i
        }
      }
      return -1
    },
    // 将英文转为ASCII码
    codeChange(string) {
      let blue_arr = ['0xFF', '0xFF', '0xFF', '0xFF', '0xFF', '0xFF', '0xFF']
      let string_arr = string.split('')
      string_arr.forEach((item, index) => {
        blue_arr[index] = '0x' + item.charCodeAt().toString(16)
      })
      // let new_arr = string_arr.map((item) => {
      //   return item.charCodeAt().toString(16)
      // })
      blue_arr.unshift('0x5A')
      blue_arr.push('0x55')
      let blue_str = blue_arr.join(' ')
      this.writeBLECharacteristicValue(blue_str)
    },
  },
}
export default global
